<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/26
 * Time: 10:08
 */

namespace Admin\Frontend\Controllers;




use Admin\Models\coop\XhCoopContact;
use Admin\Models\coop\XhCoopInfo;
use Admin\Models\crm\XhcustContact;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Cache;
use Helpers\Hrm;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Template;
use Helpers\User;
use Helpers\UserPower;

class CoopController extends ControllerBase
{


    /**
     * 检查类型
     * @param $type
     * @param string $operater
     * @return bool
     * create by dale 20180327
     */
    public function checkPower($type,$operater=''){
        if($type == 1){
            $tag = 'Coop_Agency';
        }else if($type == 2){
            $tag = 'Coop_Supply';
        }
        if($operater != ''){
            $tag .= '_'.ucfirst($operater); //首字母大写
        }
        return UserPower::checkUserPower($tag);
    }

    /**
     * 错误信息
     * @param bool $isView
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by dale 20180327
     */
    public function sendPowerMsg($isView=false){
        if($isView){
            return $this->sendViewError('没有权限');
        }else{
            return $this->sendErrorResponse(400,'缺少权限');
        }
    }


    /**
     * 获取额外权限
     *
     * @param $tag
     * @return array|bool
     * @throws \Exception
     * create by xjq 20180606
     */
    public function extraPower($tag){
        if(User::isAdmin()){
            return true;
        }
        $deps = User::getExtraPower('dep',$tag);
        $userIds = Hrm::getUserByDepId($deps);
        $newArr = [];
        foreach ($userIds as $ids){
            $newArr =array_merge($newArr,$ids);
        }
        $newArr = array_values(array_filter($newArr));

        return $newArr;
    }



    /**
     *
     * @param $type
     * @return \Phalcon\Mvc\View
     * create by dale 20180326
     */
    public function coopListAction($type){
        if(!$this->checkPower($type)){
            return $this->sendPowerMsg(true);
        }
        Assets::easyUI();
        Assets::importJs('js/coop/coopList.js');
        $this->view->pick('coop/coopList');
        Template::exists('Coop_Info', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if($this->checkPower($type,'add')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if($this->checkPower($type,'del')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'       => Template::createList('list', 'Coop_Info', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form'       => true,
            'type'       => $type,
            'power'      => $this->checkPower($type,'edit'),
        ]);
    }

    /**
     * 获取基本信息
     * @param $type
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180326
     */
    public function getInfoAction($type){
        if(!$this->checkPower($type)){
            return $this->sendPowerMsg(false);
        }
        $builder = $this->modelsManager->createBuilder()
                    ->columns('*')
                    ->from('Admin\\Models\\coop\\XhCoopInfo')
                    ->where('bDelete = 0 AND iType = :iType:',['iType' => $type] );

        if (!User::isAdmin()) {
            $conditionsArr = [
                'conditions' => 'iCreateUserId = :nowUser:',
                'bind'       => ['nowUser' => Main::getLoginUserInfo('userId')]
            ];
            if($type ==1){
                $tag = 'coopAgency';
            }else if($type == 2){
                $tag = 'coopSupply';
            }else{
                return $this->sendErrorResponse( 400 ,'未知类型');
            }
            if(User::getExtraPower('dep',$tag,null,true)){ //有扩展权限
                $userIds = $this->extraPower($tag);
                if (!is_bool($userIds)){
                    $conditionsArr['conditions'] .= " or  iCreateUserId in ({userIds:array}) ";
                    $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array('userIds' => $userIds));
                }
            }
            $builder->andWhere($conditionsArr['conditions'] , $conditionsArr['bind']);
        }

        $data = Main::runBuilderPage($builder);

        Main::runUserNameById($data['rows'],['iCreateUserId' => 'iCreateUserId','iLastModifyUserId' => 'iLastModifyUserId'],true);
        return $this->sendJsonResponse($data);
    }


    /**
     * 添加表单
     *
     * @param $type
     *
     * create by dale 20180326
     */
    public function addFormAction($type){
        if(!$this->checkPower($type,'add')){
            return $this->sendPowerMsg(true);
        }
        $this->view->pick('coop/addForm');
        Assets::select2();
        $prods = $this->getProds();
        $this->view->setVars([
            'type' => $type,
            'prods' => $prods
        ]);
    }


    /**
     * 获取商品
     *
     * @return array
     *
     * create by dale 20180327
     */
    public function getProds(){
        $sql = 'select iProdId,sProdName  from XHIms_Produce where bDelete = 0 ';
        $data = $this->db->fetchAll($sql);
        return array_column($data,'sProdName','iProdId');
    }

    /**
     * 保存信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180326
     */
    public function saveInfoAction(){
        $data = $this->request->getPost();
        if(!$this->checkPower($data['iType'],'add')){
            return $this->sendPowerMsg(false);
        }
        try{
            $this->db->begin();
            if(isset($data['iCIId'])){
                $obj = XhCoopInfo::findFirst($data['iCIId']);
            }else{
                $obj = new XhCoopInfo();
            }
            $obj->assign($data);
            if($obj->iType == 2){
                if(isset($data['sProdIds'])){
                    $obj->sProdIds = implode(',',$data['sProdIds']);
                }

            }
            if(!$obj->save()){
                return $this->sendErrorResponse(500,'保存失败');
            }


            if($obj->iType == 1){
                $depId = $this->createDep($obj);
                if($obj->iDepId == null){
                    $obj->iDepId = $depId;
                    if(!$obj->save()){
                        $this->db->rollback();
                        return $this->sendErrorResponse(500,'部门关联失败');
                    }
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 创建修改部门
     *
     * @param $obj
     * @return int
     * @throws \Exception
     *
     * create by dale 20180326
     */
    public function createDep($obj){
        try{
            $dep = XhhrmDepart::findFirst([
                'conditions' => 'bDelete = 0 AND sTag = :sTag:',
                'bind'       => ['sTag' => 'XHDL']
            ]);
            if(!$dep){
                throw new \Exception('没有创建代理部门');
            }
            if($obj->iDepId != null){
                $subDep = XhhrmDepart::findFirst($obj->iDepId);
            }else{
                $subDep = new XhhrmDepart();
            }
            $subDep->sDepName  = $obj->sName;
            $subDep->iParentId = $dep->iDepId;
            if(!$subDep->save()){
                throw new \Exception('部门保存失败');
            }
            if(Cache::exists('DepEnum')){
                Cache::delete('DepEnum');
            }
            return $subDep->iDepId;
        }catch (\Exception $e){
            throw  new \Exception($e->getMessage());
        }

    }

    /**
     * 删除
     *
     * @param $type
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180327
     */
    public function delInfoAction($type){
        $ids = $this->request->getPost('ids');
        if(!$this->checkPower($type,'del')){
            return $this->sendPowerMsg(false);
        }
        if(!$ids){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $this->db->begin();
        foreach ($ids as $id){
            $obj = XhCoopInfo::findFirst($id);
            $obj->bDelete = 1 ;
            if(!$obj->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(400,'保存失败');
            }
            if($type == 1){
                $dep = XhhrmDepart::findFirst($obj->iDepId);
                $dep->bDelete = 1;
                if(!$dep->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(400,'保存失败');
                }
            }
        }
        $this->db->commit();
        return $this->sendSuccessResponse('删除成功');

    }



    /**
     * tab页签
     *
     * @param $type
     * @param $id
     *
     * @return string
     *
     * create by dale 20180326
     */
    public function coopTabAction($type,$id){
        if(!$this->checkPower($type,'edit')){
            return $this->sendPowerMsg(false);
        }
        if(!$type || !$id){
            return $this->sendViewError('缺少参数');
        }
        $info = XhCoopInfo::findFirst($id)->toArray();
        $this->view->pick('coop/coopTab');
        Assets::select2();
        Assets::importJs('js/coop/coopTab.js');
        $prods = $this->getProds();
        $this->view->setVars([
            'info'    => json_encode($info),
            'iCIId'   => $info['iCIId'],
            'prods'   => $prods,
            'type'    => $type,
        ]);
    }


    /**
     * 联系人
     *
     * create by dale 20180326
     */
    public function contactAction($type){
        $iCIId = $this->request->getQuery('iCIId');
        $this->view->pick('coop/contact');
        Assets::easyUI();
        Assets::select2();
        Assets::importJs('js/coop/contact.js');
        Template::exists('Coop_Contact', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));//检查public/template/from/目录下是否都存在template文件夹
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if($this->checkPower($type,'add')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '增加', 'icon' => 'fa-plus');
        }
        if($this->checkPower($type,'del')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if($this->checkPower($type,'bind')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_bindAccount', 'text' => '绑定账号', 'icon' => 'fa-pencil');
        }
        if(XhCoopInfo::findFirst($iCIId)->iType == 1){
            if($this->checkPower($type,'edit')){
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_setDefault', 'text' => '设置负责人', 'icon' => 'fa-chain');
            }

        }
        $this->view->setVars(array(
            'List' => Template::createList('List', 'Coop_Contact', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ));
    }

    /**
     * 获取联系人
     *
     * @param $iCIId
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180326
     */
    public function getContactAction($iCIId){
        $builder = $this->modelsManager->createBuilder()
            ->columns('*')
            ->from('Admin\\Models\\coop\\XhCoopContact')
            ->where('bDelete = 0 AND iCIId = :iCIId:',['iCIId' => $iCIId] );

        $data = Main::runBuilderPage($builder);
        foreach ($data['rows'] as $index=> $row){
            if($row['iUserId'] != null){
                $data['rows'][$index]['info'] = '<i class="fa fa-user" style="color:#2baab1;" title="userId:'.$row['iUserId'].',staffId:'.$row['iStaffId'].'"></i>';
                if($row['bDefault'] == 1){
                    $data['rows'][$index]['info'] = '<i class="fa fa-user" style="color:#0066cc;" title="userId:'.$row['iUserId'].',staffId:'.$row['iStaffId'].'"></i>';
                }
            }else if($row['iStaffId']!=null && $row['iUserId'] == null){
                $data['rows'][$index]['info'] = '<i class="fa fa-user" style="color:green;" title="staffId:'.$row['iStaffId'].'"></i>';
            }else{
                $data['rows'][$index]['info'] = '';
            }
        }
        Main::runUserNameById($data['rows'],['iCreateUserId' => 'iCreateUserId','iLastModifyUserId' => 'iLastModifyUserId'],true);
        return $this->sendJsonResponse($data);
    }

    /**
     * 联系人表单
     *
     * @param $iCIId
     * @param $iCCId
     *
     * create by dale 20180326
     */
    public function contactFormAction($iCIId,$iCCId=null){
        $this->view->pick('coop/contactForm');
        Assets::importJs('js/coop/contactForm.js');

        $webArr = [
            'iCIId' => $iCIId,
            'type'  => XhCoopInfo::findFirst($iCIId)->iType,
        ];
        if($iCCId){
            $info = XhCoopContact::findFirst($iCCId);
            $webArr['info'] = json_encode($info);
        }

        $this->view->setVars($webArr);
    }

    /**
     * 删除
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180327
     */
    public function delContactAction($type){
        $ids = $this->request->getPost('ids');
        if(!$this->checkPower($type,'del')){
            return $this->sendPowerMsg(false);
        }
        if(!$ids){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $this->db->begin();
        foreach ($ids as $id){
            $obj = XhCoopContact::findFirst($id);
            $obj->bDelete = 1;
            if(!$obj->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(500,'删除失败');
            }
            $staff = XhhrmStaff::findFirst($obj->iStaffId);
            $staff->bDelete = 1;
            if(!$staff->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(500,'删除失败');
            }
        }
        $this->db->commit();
        return $this->sendSuccessResponse('删除成功');
    }

    /**
     * 保存联系人
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180326
     */
    public function saveContactAction(){
        $data = $this->request->getPost();
        try{
            $this->db->begin();//开始事务
            if(isset($data['iCCId']) && $data['iCCId'] != ''){
                $obj = XhCoopContact::findFirst($data['iCCId']);
            }else{
                $obj =  new XhCoopContact();
            }
            $obj->assign($data);
            if(!$obj->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(500,'保存失败');
            }
            if($obj->iType == 1){ //代理商
                $staff = XhhrmStaff::findFirst([
                    'conditions' => 'bDelete = 0 and sSelfPhone = :sSelfPhone:',
                    'bind'       => ['sSelfPhone' => $obj->sPhoneNum]
                ]);
                $contact = XhCoopContact::findFirst($obj->iCCId);

                if (!$staff) {
                    $staffId = $this->createStaff($obj);
                } else {
                    $staffId = $staff->iStaffId;
                    $contact->iUserId = $staff->iUserId;
                }
                $contact->iStaffId = $staffId;
                if(!$contact->save()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '职工信息关联失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    /**
     * 绑定账号
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale 20180327
     */
    public function bindAccountAction(){
        $this->view->pick('coop/bindAccount');
        Assets::importJs('js/coop/bindAccount.js');
        $iCCId = $this->request->getQuery('iCCId', 'int');
        if (!$iCCId) {
            return $this->sendViewError('缺少联系人id！');
        }
        $contact = XhCoopContact::findFirst($iCCId);
        if (!$contact) {
            return $this->sendViewError('找不到联系人记录！');
        }
        if($contact->sPhoneNum == null){
            return $this->sendViewError('电话为空！');
        }
        $params = [
            'columns' => 'iUserId,sUserName,sLogonName,sSelfPhone,bDisable',
            'conditions' => 'sSelfPhone = :phoneNum: OR sLogonName = :phoneNum:',
            'bind' => ['phoneNum' => $contact->sPhoneNum]
        ];
        if ($contact->iUserId) {
            $params['conditions'] .= ' OR iUserId = :userId:';
            $params['bind']['userId'] = $contact->iUserId;
        }
        $userList = XhsysUser::find($params)->toArray();
        if (!$userList) {
            return $this->sendViewError('找不到联系人所属账号!');
        }
        if ($contact->iUserId) {
            foreach ($userList as $index => $user) {
                if ($contact->iUserId == $user['iUserId']) {
                    $userList[$index]['sUserName'] .= "<font style='color: red;'>(已绑定)</font>";
                }
            }
        }
        return $this->view->setVar('accountList', $userList);
    }


    /**
     * 保存绑定
     *
     * @param bool $bind
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180327
     */
    public function saveBindAction($bind = false)
    {
        try{
            $iCCId = $this->request->getPost('iCCId', 'int');
            $userId = $this->request->getPost('userId', 'int');
            if (!$iCCId || !$userId) {
                return $this->sendErrorResponse(400,'缺少参数');
            }
            $contact = XhCoopContact::findFirst($iCCId);
            if (!$contact) {
                return $this->sendErrorResponse(500,'找不到联系人');
            }
            $this->db->begin();
            if ($bind) {
                if ($userId != $contact->iUserId) {
                    return $this->sendErrorResponse(500,'该记录未关联');
                }
                $contact->iUserId = null;
            } else {
                $contact->iUserId = $userId;
            }
            if (!$contact->save()) {
                $this->db->rollback();
                return $this->sendErrorResponse(500,'保存失败');
            }
            if(!$contact->iStaffId){
                $this->db->rollback();
                return $this->sendErrorResponse(500,'职工未录入');
            }
            $staff = XhhrmStaff::findFirst($contact->iStaffId);
            if(!$staff){
                $this->db->rollback();
                return $this->sendErrorResponse(500,'未找到职工信息');
            }
            $staff->iUserId = $contact->iUserId;
            if(!$staff->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(500,'职工信息保存失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');

        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 改变默认值
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180327
     */
    public function changeDefaultAction()
    {
        try{
            $iCCId = $this->request->getPost('iCCId', 'string') ;
            $iCIId  = $this->request->getPost('iCIId', 'string') ;
            if(!$iCCId || !$iCIId){
                return $this->sendErrorResponse(400,'缺少参数');
            }
            $contact = XhCoopContact::findFirst($iCCId);
            if ($contact->bDefault == 1) {
                return $this->sendErrorResponse(400,'已经是负责人不需要在设置');
            }
            $this->db->begin(); //开启事务
            $objs = XhCoopContact::find([
                'conditions' => 'bDelete=:bDelete: AND iCIId=:iCIId:',
                'bind' => ['bDelete' => 0, 'iCIId' => $iCIId],
            ]);
            if ($objs) {
                foreach ($objs as $obj) {
                    $obj->bDefault = 0;
                    if (!$obj->save()) {
                        $this->db->rollback();
                        return  $this->sendErrorResponse(500,'取消其他联系人失败');
                    }
                    if($obj->iStaffId){
                        $staff = XhhrmStaff::findFirst($obj->iStaffId);
                        $staff->sChargeDeps = null;
                        if(!$staff->save()){
                            $this->db->rollback();
                            return  $this->sendErrorResponse(500,'取消部门负责人');
                        }
                    }
                }
            }
            $contact->bDefault = 1;
            if (!$contact->save()) {
                $this->db->rollback();
                return $this->sendErrorResponse(500,'设置默认失败');
            }
            if($contact->iStaffId){
                $depId = XhCoopInfo::findFirst($iCIId)->iDepId;
                $staff =  XhhrmStaff::findFirst($contact->iStaffId);
                $staff->sChargeDeps = $depId;
                if(!$staff->save()){
                    $this->db->rollback();
                    return  $this->sendErrorResponse(500,'设置部门负责人失败');
                }

            }

            $this->db->commit();
            return $this->sendSuccessResponse('更新成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * 创建账号
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180327
     */
    public function createAccountAction(){
        try{
            $userName = $this->request->getPost('userName','string');
            $phoneNum = $this->request->getPost('phoneNum','string');
            $iCCId    = $this->request->getPost('iCCId' , 'string');
            if(!$userName || !$phoneNum){
                return $this->sendErrorResponse(400,'缺少参数');
            }
            if (XhCoopContact::findFirst($iCCId)->iType == 2){
                $res = $this->createNewAccount($phoneNum , $userName , '123456' , 12);
            }else{
                $res = $this->createNewAccount($phoneNum , $userName);
            }
            if($res){
                return $this->sendSuccessResponse('保存成功');
            }else{
                return $this->sendErrorResponse(500,'失败');
            }
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * @param $phoneNum
     * @param $staffName
     * @param string $pwd
     * @param int $type  11 => 供应商   12 => 代理商
     * @return bool
     * @throws \Exception
     */
    private function createNewAccount($phoneNum, $staffName, $pwd = '123456',$type = 11 )
    {
        $user = new XhsysUser();
        $user->sLogonName   = $phoneNum;
        $user->sUserName    = $staffName;
        $user->sLogonPwd    = strtoupper(md5($pwd));
        $user->sSelfPhone   = $phoneNum;
        $user->iUserType    = $type;
        $user->bCompany     = 1;
        return $user->insertAfterOld();
//        static $httpClient;
//        if (!$httpClient) {
//            $url = Main::getConfigByName('hrm')['registerUrl'];
//            if (!$url) {
//                throw new \Exception('缺少registerUrl配置');
//            }
//            $httpClient = new HttpClient($url);
//        }
//        $response = $httpClient->post('main/register-staff', ['K' => json_encode(['sSelfPhone' => $phoneNum, 'sUserName' => $staffName, 'sLogonPwd' => strtoupper(md5($pwd)),'iUserType'=>$type])]);
//        if (!$response->isSuccess()) {
//            throw new \Exception('请求失败：' . $response->error);
//        }
//        $body = $response->toArray();
//        if ($body['R'] != 200) {
//            throw new \Exception($body['M'] ?: $response->body);
//        }
//        return true;
    }



    /**
     * 创建职工
     * @param $obj
     * @return int
     * @throws \Exception
     * create by dale 20180326
     */
    public function createStaff($obj){
        try{
            $staff = new XhhrmStaff();
            $staff->sStaffName = $obj->sName;
            $depId = XhCoopInfo::findFirst($obj->iCIId)->iDepId;
            if(!$depId){
                throw  new \Exception('未找到所属部门');
            }
            $staff->sDepIds = $this->getDepIds($depId);
            $staff->sSelfPhone = $obj->sPhoneNum;
            if(!$staff->save()){
                throw  new \Exception('职工保存失败');
            }
            return $staff->iStaffId;
        }catch (\Exception $e){
            throw  new \Exception($e->getMessage());
        }
    }

    /**
     * 获取到sDepIds
     *
     * @param $iDepId
     * @return string
     *
     * created by dale 2017817
     */
    public function getDepIds($iDepId)
    {
        $iDepIds = [];
        $iDepIds = $this->recursionForIds($iDepId, $iDepIds);
        $sDepIds = ',';
        foreach ($iDepIds as $id) {
            $sDepIds .= $id . ',';
        }

        return $sDepIds;
    }

    /**
     * 循环递归获取父部门id
     *
     * @param $iDepId
     * @param $array
     * @return array
     *
     * created by dale 2017817
     */
    public function recursionForIds($iDepId, $array)
    {
        $nowDep = XhhrmDepart::findFirst([
            'conditions' => 'bDelete=0 AND iDepId=:iDepId:',
            'bind' => array('iDepId' => $iDepId)
        ]);
        $array[] = $nowDep->iDepId;
        if ($nowDep->iParentId == 0) {
            return $array;
        } else {
            return $this->recursionForIds($nowDep->iParentId, $array);
        }
    }


}